package com.steam.xbcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.steam.xbcc.domain.CourseOrder;
import com.steam.xbcc.dto.PayExtParamsDto;
import com.steam.xbcc.enums.GlobalExceptionCode;
import com.steam.xbcc.service.ICourseOrderService;
import com.steam.xbcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "tx-order-pay-consumer-group",
        topic = "tx-pay-notify-topic",
        selectorExpression = "tx-pay-notify-tag",
        messageModel = MessageModel.BROADCASTING
)
public class OrderPayAsyncNotifyTxConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.业务校验
        byte[] body = messageExt.getBody();
        String paramStr = new String(body, StandardCharsets.UTF_8);
        PayExtParamsDto payExtParamsDto = JSON.parseObject(paramStr, PayExtParamsDto.class);
        AssertUtil.isNotNull(payExtParamsDto, GlobalExceptionCode.ERROR);
        String orderNo = payExtParamsDto.getOrderNo();
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);
        if (courseOrder == null){
            log.error("支付结果处理，查询课程订单失败，订单号为：{}", orderNo);
            // 记录日志表
            return;
        }
        if (CourseOrder.WAIT_PAY_STATUS.equals(courseOrder.getStatusOrder())){
            courseOrder.setStatusOrder(CourseOrder.SUCCESS_PAY_STATUS);
            courseOrder.setUpdateTime(new Date());
            courseOrderService.updateById(courseOrder);
        }
    }
}